#!/usr/bin/env python3
import sys
import re
import os
from PySide6.QtWidgets import QWidget, QApplication, QLineEdit, QMainWindow, QTextBrowser


class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.paths = ""  # ==> 默认文本内容
        self.setWindowTitle('文件拖入')  # ==> 窗口标题
        self.resize(500, 400)  # ==> 定义窗口大小
        self.textBrowser = QTextBrowser()
        self.setCentralWidget(self.textBrowser)  # ==> 定义窗口主题内容为textBrowser
        self.setAcceptDrops(True)  # ==> 设置窗口支持拖动（必须设置）

    # 鼠标拖入事件
    def dragEnterEvent(self, event):
        self.setWindowTitle('dragEnterEvent')
        for it in event.mimeData().urls():
            file = it.toLocalFile()  # ==> 获取文件路径
            if file not in self.paths:  # ==> 去重显示
                print("拖拽的文件 ==> {}".format(file))
                new_path = self.handler_file(file)
                self.paths += file + "-->" + new_path+ "\n"
                self.textBrowser.setText(self.paths)

        # 鼠标放开函数事件
        event.accept()

    # 处理文件
    def handler_file(self,path):
        file=os.path.basename(path)
        pre,suf = os.path.splitext(file)
        dst_file = None
        if re.search('[a-zA-Z]+-[\d]+',pre):
            m = re.search('[a-zA-Z]+-[\d]+',pre)
            dst_file = m.group(0)

        # xxx123
        elif re.search('[a-zA-Z]+[\d]+',pre):
            m = re.search('[a-zA-Z]+[\d]+',pre)
            org = m.group(0)
            rules = re.compile('[0-9]')
            ret = re.search(rules,org)
            idx = ret.span()[0]
            name = org[0:idx]   # xxx
            number = org[idx:]  # 123
            dst_file = name+'-'+number
            
        else:
            print("不能匹配文件规则")
            dst_file = pre

        dst_path = os.path.dirname(path)+'/'+dst_file+suf
        print("处理结果:",dst_path)
        os.rename(path,dst_path)
        return dst_path


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())